package org.zxp.ConcurrentLatch;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class LatchExcutorBlockingQueueManager {

    //线程池最大数量
    public static BlockingQueue<String> executorQueue = new LinkedBlockingQueue<String>(Constants.MAX_EXCUTOR_COUNT);
    //已经拿到的线程池
    public static Map<String,ExecutorService> excutorMap = new HashMap<String, ExecutorService>();


//    public static  int a = 0;
    public static ExecutorService getExcutor(int threadCount) throws InterruptedException {
        synchronized (executorQueue) {
            executorQueue.put(UUID.randomUUID().toString());
//            System.err.println("第"+(++a)+"次运行");
            ExecutorService excutor = null;
            if(threadCount <= Constants.CURRENT_MAX_POOL_COUNT){
                excutor = Executors.newFixedThreadPool(threadCount);
            }else{
                excutor = Executors.newFixedThreadPool(Constants.CURRENT_MAX_POOL_COUNT);
            }
            return excutor;
        }
    }

    public static ExecutorService getExcutor() throws InterruptedException {
        synchronized (executorQueue) {
            executorQueue.put(UUID.randomUUID().toString());
            ExecutorService excutor = Executors.newFixedThreadPool(Constants.CURRENT_MAX_POOL_COUNT);
            return excutor;
        }
    }

    public static void takeExcutor(ExecutorService excutor) throws InterruptedException {
        excutorMap.put(UUID.randomUUID().toString(),excutor);
        executorQueue.take();
        excutor.shutdown();
        excutor.shutdownNow();
    }

    public static void print(){
        System.out.println("当前阻塞队列长度"+executorQueue.size());
        for (String a:excutorMap.keySet()){
            System.out.println("isShutdown:"+excutorMap.get(a).isShutdown()+"  isTerminated:"+excutorMap.get(a).isTerminated());
        }
    }



}
